// @ts-nocheck==
import { login, getUserInfo, setSelfInfo } from "amtf/api/user"
import { jsonInBlacklist } from "amtf/api/jwt"
// import router from "@/router/index"
import { defineStore } from "pinia"
import { ref, computed, watch, reactive } from "vue"
import { Cookies, SessionStorage, Loading, LocalStorage } from "quasar" // 导入 Quasar 的 Loading
import * as util from "amtf/utils"
import 默认头像 from "amtf/assets/xiao-h.png"
import { useRoute, useRouter } from "vue-router"
import useApi from "amtf/api/use增查api"
// import cookie from "js-cookie"
import { useCookies } from '@vueuse/integrations/useCookies'
import { useStorage } from '@vueuse/core'

export const useUserStore = defineStore("user", () => {
  const router = useRouter();
  const route = useRoute();

  const a = reactive({
    记住我: true,
  })

  const userInfo = reactive({
    uuid: "",
    nick_name: "",
    avatar: "",
    authority: {},
  })

  // if (Cookies.get('userInfo')) {
  if (LocalStorage.getItem('userInfo')) {
    util.对象重予(userInfo, LocalStorage.getItem('userInfo'))
  }

  // console.log(`LocalStorage.getItem("token") 👉`,LocalStorage.getItem("token"))
  // console.log(`Cookies.get("x-token") 👉`,Cookies.get("x-token"))
  // console.log(`cookie.get("x-token") 👉`,cookie.get("x-token"))
  // const token = ref(LocalStorage.getItem("token") || Cookies.get("x-token") || "")
  const token = useStorage('token', '')
  // const xToken = useCookies('x-token')
  const xToken = useCookies(['x-token']);

  const 显头像 = computed(() => {
    let url = userInfo.avatar ? userInfo.avatar : 默认头像
    url = util.成url(url)
    // console.log(`url 👉`,url)
    return url
  })

  const setUserInfo = val => {
    // userInfo = val
    util.对象重予(userInfo, val)
    // Cookies.set('userInfo', userInfo)
    LocalStorage.set('userInfo', userInfo)
  }

  // const setToken = val => {
  //   console.log(`setToken ing👇`)
  //   token.value = val
  //   // if (a.记住我) {
  //   //   console.log(`Cookies.set ing token.value👇`,token.value)
  //   //   Cookies.set('x-token', token.value)
  //   // } else {
  //   //   LocalStorage.set('token', token.value)
  //   // }
  //   LocalStorage.set('token', token.value)
  // }
  const setToken = (val) => {
    token.value = val
    // xToken.value = val
    xToken.set('x-token', val);
  }

  const ResetUserInfo = (value = {}) => {
    util.对象重予(userInfo, {
      ...userInfo,
      ...value,
    })
  }

  const GetUserInfo = async () => {
    const res = await getUserInfo()
    if (res.code === 0) {
      console.log(`res.data.userInfo 👉`, res.data.userInfo)
      setUserInfo(res.data.userInfo)
    }
    return res
  }

  const LoginIn = async loginInfo => {
    Loading.show({
      message: "登录中，请稍候...",
      spinnerColor: "primary",
      spinnerSize: 140,
      customClass: "custom-loading-class",
    })
    const res = await login(loginInfo)
    // 登陆失败，直接返回
    if (res.code !== 0) {
      Loading.hide()
      return false
    }
    // 登陆成功，设置用户信息和权限相关信息
    console.log(`res.data 👉`, res.data)
    // util.对象重予(单项, res.data.user)

    setUserInfo(res.data.user)
    setToken(res.data.token)

    const redirect = route.query.redirect
    console.log(`redirect 👉`, redirect)
    if (redirect) {
      const decodedRedirect = decodeURIComponent(redirect)
      console.log(`decodedRedirect 👉`, decodedRedirect)
      // router.push({ path: decodedRedirect })
      window.location.hash = decodedRedirect;
    } else {
      // router.push("/")
      window.location.hash = '/';
    }

    const isWin = ref(/windows/i.test(navigator.userAgent))
    if (isWin.value) {
      LocalStorage.setItem("osType", "WIN")
    } else {
      LocalStorage.setItem("osType", "MAC")
    }

    ws.send(JSON.stringify({
      "登录完成尝试跳转": "……"
    }));
    // 全部操作均结束，关闭loading并返回
    Loading.hide()
    return true
  }

  /* 登出*/
  const LoginOut = async () => {
    console.log(`LoginOut ing👇`)
    const res = await jsonInBlacklist()
    // 登出失败
    if (res.code !== 0) {
      console.log(`登出失败 res👉`, res)
      return
    }
    await ClearStorage()
    // 把路由定向到登录页，无需等待直接reload
    router.push({ name: "Login", replace: true })
    window.location.reload()
  }

  // const ClearStorage = async () => {
  //   console.log(`ClearStorage ing👇`)
  //   token.value = ""
  //   SessionStorage.clear()
  //   LocalStorage.removeItem("token")
  //   Cookies.remove("x-token")
  //   Cookies.remove("userInfo")
  //   LocalStorage.removeItem("origin_setting")
  // }
  const ClearStorage = async () => {
    console.log(`ClearStorage ing👇`)
    token.value = ''
    // xToken.value = ''
    xToken.set('x-token', '');
    sessionStorage.clear()
    localStorage.removeItem('originSetting')
  }

  const api = useApi("huiyuangl/huiyuan")
  const 查能量 = async () => {
    console.log(`userInfo 👉`, userInfo)
    const res = await api.查({ id: userInfo.ID })
    console.log(`use详情_抽屉式 查res 👉`, res)
    if (res.code != 0) return {}
    // const 还有时间 = Cookies.get("daoqi_date")
    const 单项 = res.data
    console.log(`单项 👉`, 单项)
    const res2 = {
      nengliang: false,
      已充电: 单项.充电,
      更上层楼: 单项.更上层楼
    }
    const 剩余 = 单项.剩余 / 86400000
    if (剩余 > 0) {
      res2.nengliang = true;
    }
    console.log(`res2 👉`, res2)
    // console.log('kk: ',kk);
    return res2
  };
  // 查能量()

  return {
    查能量,
    显头像,
    userInfo,
    token,
    ResetUserInfo,
    GetUserInfo,
    LoginIn,
    LoginOut,
    setToken,
    ClearStorage,
  }
})
